import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';

class DensityUtil {
  static MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);
  static double _width = mediaQuery.size.width;
  static double _height = mediaQuery.size.height;
  static double _topbarH = mediaQuery.padding.top;
  static double _botbarH = mediaQuery.padding.bottom;
  static double _pixelRatio = mediaQuery.devicePixelRatio;
  static var _ratio;

  static init(int number) {
    int uiwidth = number is int ? number : 375;
    _ratio = _width / uiwidth;
  }

  static onepx() {
    return 1 / _pixelRatio;
  }

  static screenW() {
    return _width;
  }

  static screenH() {
    return _height;
  }

  static padTopH() {
    return _topbarH;
  }

  static padBotH() {
    return _botbarH;
  }

  static px(number) {
    if (!(_ratio is double || _ratio is int)) {
      DensityUtil.init(375);
    }
    print(_ratio);
    return number * _ratio;
  }

  static realWDivH(double wRatio, double ratio) {
    return _width * wRatio / ratio;
  }


  static TargetPositionModel getPostion(GlobalKey key) {
    try {
      final RenderBox renderBoxRed = key.currentContext
          .findRenderObject() as RenderBox;
      Size size = renderBoxRed.paintBounds.size;
      final state =
      key.currentContext.findAncestorStateOfType<NavigatorState>();
      Offset offset;
      if (state != null) {
        offset = renderBoxRed.localToGlobal(Offset.zero,
            ancestor: state.context.findRenderObject());
      } else {
        offset = renderBoxRed.localToGlobal(Offset.zero);
      }
      return TargetPositionModel(size, offset);
    } catch (e) {
      return null;
    }
  }
}

class TargetPositionModel {
  final Size size;
  final Offset offset;

  TargetPositionModel(this.size, this.offset);

  Offset get center => Offset(
    offset.dx + size.width / 2,
    offset.dy + size.height / 2,
  );
  double getBiggerSpaceBorder(Size size) {
    double maxDistanceX =
    center.dx > size.width / 2 ? center.dx : size.width - center.dx;
    double maxDistanceY =
    center.dy > size.height / 2 ? center.dy : size.height - center.dy;
    return max(maxDistanceX, maxDistanceY);
  }
}
